# -*- coding: utf-8 -*-
"""
Created on Thu Aug 08 22:48:35 2013

@author: Jeanhwea
"""

from email.mime.base import MIMEBase
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email import utils, encoders
import mimetypes, sys
import smtplib

password = sys.argv[1]
frm = sys.argv[2]
to = sys.argv[3]
sub = sys.argv[4]
message = ' '.join(sys.argv[5:])


def attachment(filename):
    fd = open(filename, 'rb')
    mimetype, mimeencoding = mimetypes.guess_type(filename)
    if mimeencoding or (mimetype is None):
        mimetype = 'application/octet-stream'
    maintype, subtype = mimetype.split('/')
    if maintype == 'text':
        retval = MIMEText(fd.read(), _subtype=subtype)
    else:
        retval = MIMEBase(maintype, subtype)
        retval.set_payload(fd.read())
        encoders.encode_base64(retval)
    retval.add_header('Content-Disposition', 'attachment',
            filename = filename)
    fd.close()
    return retval

msg = MIMEMultipart()
msg['To'] = to
msg['From'] =  'DaDada'+ ' ' + frm
msg['Subject'] = sub
msg['Date'] = utils.formatdate(localtime = True)
#msg['Message-ID'] = utils.make_msgid()
# following two statements is to hide your pc idhost
idhost = '126.com' # a fake idhost
msg['Message-ID'] = utils.make_msgid(idstring='Coremail').split('@')[0] + '@' + idhost + '>'
# done
body = MIMEText(message, _subtype='plain', _charset='utf-8')
msg.attach(body)
#for filename in sys.argv[1:]:
#    msg.attach(attachment(filename))
print msg.as_string()

host = 'smtp.126.com' if (password[0:4] != '1106') else 'smtp.163.com'

smtp = smtplib.SMTP()
smtp.connect(host)
smtp.login(frm, password)
smtp.sendmail(frm, to, msg.as_string())
smtp.quit()